package com.zzyl.intercept;


import com.zzyl.constant.JwtConstants;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.HttpStatus;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader(JwtConstants.TOKEN_KEY);

        //判断token是否为空
        if (StringUtils.isEmpty(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        //解析token
        try{
            Claims claims = JwtUtil.parseJWT(jwtProperties.getBase64EncodedSecretKey(), token);
            //解析成功获取memberId
            Long memberId = claims.get(JwtConstants.MEMBER_ID, Long.class);
            //解析失败
            if(memberId == null || memberId <= 0 ){
                response.setStatus(HttpStatus.UNAUTHORIZED);
                return false;
            }else{
                // 把memberId保存到ThreadLocal
                UserThreadLocal.set(memberId);
                log.info("保存用户id到TL：{}", memberId);
                return true;
            }
        }catch (Exception e){
                log.error(e.getMessage(), e);
                response.setStatus(HttpStatus.UNAUTHORIZED);
                return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
